<template>
  <!-- 服务管理 -->
  <div class="innerPageTable-box-OneTwo value-set-list-wrap innerPageTable-out-flex">
    <InnerPageTable ref="valueSetTable" :config="pageTableConfig" v-if="showTable">
      <div slot="table-bar" v-if="fromPage == 'creater'">
        <RPButton
          v-if="!onlyRead && hasPermission('QUESTION_ANS_INSERT')"
          :disabled="createDisabled"
          optType="create"
          type="info"
          text="新建"
          @click="goPlanCreatePage"
        />
        <!-- 为了不让最后一个按钮的样式有问题，特别多加一个无意义按钮 -->
        <RPButton optType="create" type="info" text="" style="display:none" />
      </div>
    </InnerPageTable>
  </div>
</template>

<script>
import { columnList } from './columns'
import editAndDetail from './questionnaireEditAndDetail.vue'
import questionnaireApi from '@/api/questionnaire.js'
import coverApi from '../../api/cover'
import { approvalMix } from '@/views/todoCenter/myApproval/approval-mix'
import { PROCESS_STATUS_LIST, PROCESS_STATUS_MAP } from '@/tools/common.js'
import permission from '@/mixin/permission'

export default {
  name: 'questionnaireList',
  components: {},
  mixins: [approvalMix, permission],
  props: {
    createbtnShow: {
      type: Boolean,
      default: false
    },
    code: {
      type: String,
      detault: ''
    },
    parentCode: {
      type: String,
      detault: ''
    },
    uploadUrl: {
      type: String,
      detault: ''
    },
    fromPage: {
      type: String,
      default: 'creater'
    },
    onlyRead: {
      type: Boolean,
      default: false
    },
    bussinessCode: {
      type: String,
      default: ''
    }
  },
  data() {
    return {
      showTable: false,
      ansConfig: {},
      anss: [],
      writePermission: true,
      processStatusList: PROCESS_STATUS_LIST,
      menuNo: this.fromPage == 'creater' ? 'implementation-plan' : 'summary-implementation-plan',
      useApiGetData: true,
      planLevels: [],
      businessUnit: [],
      categoryInitiatives: [],
      detailsInitiatives: [],
      pageTableConfig: {
        loadDataFn: this.getServiceList,
        columns: columnList.bind(this)(this.onlyRead),
        autoFirst: false, //默认 就是 false, 要配置在这里
        onSelectionChange: this.onSelectionChange,
        border: true,
        pageSize: 100
      },
      searchForm: {
        stype: '',
        mtype: '',
        code: '',
        wfStatus: '',
        startDate: '',
        startStringDate: '',
        endDate: '',
        endStringDate: '',
        taskdesc: '',
        taskQuarter: '',
        currentStatus: '',
        allDataFlag: '1',
        parentCode: this.parentCode,
        fromPage: this.fromPage,
        self: this
      },
      columnList: this.fromPage != 'creater' ? this.deleteField(columnList, 'wfStatusName') : columnList,
      ids: []
    }
  },
  computed: {
    createDisabled() {
      if (this.writePermission === false) {
        return true
      } else {
        return false
      }
    }
  },
  mounted: function() {
    if (this.onlyRead) {
      this.showTable = true
      this.$nextTick(() => {
        this.searchValueSet()
      })
    } else {
      questionnaireApi.getAnsByUserId({ userCode: window.sessionStorage.userCode }).then(res => {
        this.ansConfig = res.data.data
        this.anss = res.data.data.anss.split(',')
        this.showTable = true
        this.$nextTick(() => {
          this.searchValueSet()
        })
      })
    }
  },
  methods: {
    getConfig() {},
    init() {
      //   if (this.useApiGetData) {
      //     coverApi.getRptReportTrgnodePList({ reportName: '数字化转型专项实施方案任务表' }).then(res => {
      //       this.planLevels = res.data.data
      //       if (this.fromPage != 'creater') {
      //         this.searchForm.code = this.bussinessCode
      //       }
      //       // this.searchForm.code = this.planLevels[0].nodeName
      //       this.$nextTick(() => {
      //         this.searchValueSet()
      //       })
      //     })
      //     this.categoryInitiatives = categoryInitiatives
      //     this.searchForm.stype = ''
      //   } else {
      //     this.planLevels = planLevel
      //     if (this.createbtnShow) {
      //       // this.searchForm.code = this.planLevels[0].vsiValue
      //       // this.categoryInitiatives = this.planLevels[0].children
      //       this.searchForm.stype = ''
      //     } else {
      //       if (this.bussinessCode) {
      //         this.searchForm.code = this.bussinessCode
      //         this.categoryInitiatives = this.planLevels.find(item => item.vsiValue == this.bussinessCode)
      //           ? this.planLevels.find(item => item.vsiValue == this.bussinessCode).children
      //           : []
      //         this.detailsInitiatives = []
      //       }
      //     }
      //     this.searchValueSet()
      //   }
    },
    url(type, pathname) {
      return window.RPConfig[type] + pathname
    },
    goDetail(row) {
      let code = this.createbtnShow ? this.searchForm.code : this.code
      new this.$sidelipPage(
        editAndDetail,
        {
          props: {
            anss: this.anss,
            ansConfig: this.ansConfig,
            id: row.id || '',
            disabledPage: true,
            code: code,
            parentCode: this.parentCode,
            fromPage: this.fromPage,
            dataStatus: Number(row.ansStatus)
          }
        },
        data => {
          data && this.searchValueSet()
        }
      )
    },
    goEdit(row) {
      let code = this.createbtnShow ? this.searchForm.code : this.code
      new this.$sidelipPage(
        editAndDetail,
        {
          props: {
            anss: this.anss,
            ansConfig: this.ansConfig,
            id: row.id || '',
            code: code,
            parentCode: this.parentCode,
            Isedit: true,
            dataStatus: Number(row.ansStatus),
            fromPage: this.fromPage,
            writePermission: this.writePermission
          }
        },
        data => {
          let { pageNum } = this.$refs['valueSetTable'].param
          data && this.searchValueSet(pageNum)
        }
      )
    },
    goPlanCreatePage(associationData) {
      if (!Array.isArray(associationData)) {
        associationData = []
      }
      new this.$sidelipPage(
        editAndDetail,
        {
          props: {
            anss: this.anss,
            ansConfig: this.ansConfig,
            code: '',
            parentCode: this.parentCode,
            fromPage: this.fromPage,
            associationData,
            fromAction: 'updateProgress'
          }
        },
        data => {
          data && this.searchValueSet()
        }
      )
    },
    getServiceList(tableObj) {
      //         当有查看权限时，按钮显亮，否则就置灰
      // 进入：入参，提交状态为ansStatus 1，buName 为空，buCode为空

      // 当有填报权限时，按钮显亮，否则就置灰
      // 进入：入参，buName 当前登录人的业务单元名称，buCode 当前登录人的业务单元编码
      if (!this.ansConfig) {
        return
      }
      let { responseProcess, param } = tableObj
      let permission = {}
      if (this.onlyRead) {
        permission.ansStatus = 1
      } else {
        permission.ansStatus = undefined
        permission.buCode = this.ansConfig.areanames[0].key
        permission.buName = this.ansConfig.areanames[0].value
      }
      questionnaireApi
        .findList({
          ...permission,
          currentPage: param.pageNum,
          pageSize: param.pageSize
        })
        .then(res => {
          let records = res.data.data
          responseProcess({
            pageNum: 1,
            pageSize: 10,
            pages: 1,
            records,
            total: records.length
          })
        })
    },
    searchValueSet(pageNum = null) {
      this.$refs['valueSetTable'].load(this.searchForm, pageNum)
    },
    onSelectionChange(selection) {
      this.ids = []
      selection.forEach(element => {
        // console.log(element)
        this.ids.push({
          id: element.id,
          wfStatus: element.wfStatus,
          planName: element.planName,
          taskQuarter: element.taskQuarter
        })
      })
    },
    getUrl(type, pathname) {
      return window.RPConfig[type] + pathname
    },
    // 导出
    listExport(ids) {
      this.$confirm({
        title: '导出',
        content: '是否要批量导出?'
      }).then(() => {
        const url = window.origin + '/' + this.getUrl('itShare', `/wfRptPlantask/listExport`)
        coverApi.downloadFile2(url, ids)
      })
    },
    // 批量导出
    batchExport() {
      if (this.ids.length === 0) {
        this.$Message.error({
          content: '请选择数据后再进行操作',
          duration: 3
        })
        return
      }
      const ids = []
      this.ids.forEach(item => {
        ids.push(item.id)
      })
      this.listExport(ids)
    },
    // 批量导出最新数据
    batchExportNewest() {
      this.$confirm({
        title: '导出',
        content: '是否要导出最新数据?'
      }).then(() => {
        const url = window.origin + '/' + this.getUrl('itShare', `/wfRptPlantask/listExport/last`)
        coverApi.downloadFile2(url)
      })
    },
    // 批量删除
    batchDel() {
      if (this.ids.length === 0) {
        this.$Message.error({
          content: '请选择数据后再进行操作',
          duration: 3
        })
        return
      }
      const ids = []
      this.ids.forEach(item => {
        // 状态为1(待提交)时可以删除
        if (item.wfStatus == 1 && this.ids.filter(e => e.wfStatus == 1).length === this.ids.length) {
          ids.push(item.id)
        }
      })
      if (ids.length > 0) {
        this.deleteFun(ids)
      } else {
        this.$Message.error({
          content: '仅状态为待提交的数据可以删除，请重试',
          duration: 3
        })
      }
    },
    // 中期批量删除
    midtermBatchDel() {
      if (this.ids.length === 0) {
        this.$Message.error({
          content: '请选择数据后再进行操作',
          duration: 3
        })
        return
      }
      const ids = []
      this.ids.forEach(item => {
        ids.push(item.id)
      })
      this.midterDeleteFun(ids)
    },
    // 批量提交
    batchSubmit() {
      if (this.ids.length === 0) {
        this.$Message.error({
          content: '请选择数据后再进行操作',
          duration: 3
        })
        return
      }
      const selectedData = []
      this.ids.forEach(item => {
        // 状态为1提交
        if (item.wfStatus == 1 && this.ids.filter(e => e.wfStatus == 1).length === this.ids.length) {
          selectedData.push(item)
        }
      })
      if (selectedData.length > 0) {
        this.commitFun(selectedData)
      } else {
        this.$Message.error({
          content: '仅状态为待提交的数据可以提交，请重试',
          duration: 3
        })
      }
    }
  },
  directives: {}
}
</script>
<style lang="less" scoped>
/deep/.ivu-table-border td {
  border-right: 0;
}

/deep/.ivu-table-border th {
  border-right: 0;
}

/deep/.ivu-table-wrapper-with-border {
  border: 0;
}

/deep/.ivu-table-border:after {
  width: 0;
}

/deep/.table-bar button:last-child {
  color: #ffffff;
  background-color: #ff6f4b;
  border-color: #ff6f4b;
}

/deep/ .handle-cus {
  font-size: 18px;
  &:hover {
    color: #ff6f4b;
    cursor: pointer;
  }
}
</style>
